package biz

import (
	"encoding/json"
	"regexp"
	"strings"
	"time"
	"transfer-service/internal/global"
	"transfer-service/internal/model/const/anti"
	"transfer-service/internal/model/dto"

	mqtt "github.com/eclipse/paho.mqtt.golang"
	"github.com/go-kratos/kratos/v2/log"
)

type DroneUseCase struct {
	log              *log.Helper
	websocketUseCase *WebsocketUseCase
}

func NewDroneUseCase(logger log.Logger,
	websocketUseCase *WebsocketUseCase,
) *DroneUseCase {
	return &DroneUseCase{
		log:              log.NewHelper(log.With(logger, "module", "internal/biz/Drone")),
		websocketUseCase: websocketUseCase,
	}
}

func (s *DroneUseCase) TransferData() {
	address := global.BC.GetMiddleware().GetMqtt().GetGovNet().GetAddress()
	val, ok := global.MQTTList.Load(address)
	if !ok {
		global.LOG.Error("从mqtt map中获取客户端异常: address: %s", address)
		return
	}
	client := val.(mqtt.Client)
	token := client.Subscribe(anti.DRONE_LOCATE_TOPIC, 0, s.handlerLocateInfo)
	if !token.WaitTimeout(5 * time.Second) {
		s.log.Errorf("订阅主题 %s 超时", anti.DRONE_LOCATE_TOPIC)
		return
	}
	if token.Error() != nil {
		s.log.Errorf("订阅主题 %s 失败: %v", anti.DRONE_LOCATE_TOPIC, token.Error())
	} else {
		s.log.Infof("成功订阅主题: %s,broker 地址：%s", anti.DRONE_LOCATE_TOPIC, address)
	}
}

func (s *DroneUseCase) handlerLocateInfo(client mqtt.Client, message mqtt.Message) {
	jsonObj := map[string]any{}
	err := json.Unmarshal(message.Payload(), &jsonObj)
	if err != nil {
		s.log.Error("反序列化失败：", err)
		return
	}
	// 正则表达式匹配中间的部分
	re := regexp.MustCompile(`/([^/]+)/osd`)

	// 查找匹配的部分
	matches := re.FindStringSubmatch(message.Topic())
	sn := ""
	if len(matches) > 1 {
		sn = matches[1]
	} else {
		global.LOG.Error("匹配sn失败", err)
	}
	// 是以 15 或 4L 开头
	if !strings.HasPrefix(sn, "15") || !strings.HasPrefix(sn, "4L") {
		return
	}

	d := &dto.DockOsdMessage{
		Version:   "1.0",
		Timestamp: time.Now().Unix(),
		BizCode:   "device_osd",
		Data: &dto.DockOsdData{
			Host: jsonObj["data"],
			Sn:   sn,
		},
	}
	err = s.websocketUseCase.BroadcastMessage(d)
	if err != nil {
		global.LOG.Error("数据转发失败：", err)
		return
	}
	s.log.Debug("无人机定位数据消息转发成功：", d)
	return
}
